/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AddForeignKeyDialog.java
 *
 * Created on May 27, 2012, 11:33:08 PM
 */
package gui;

import dao.ExecForeignkeyXML;
import dao.ExecIdXML;
import dao.ExecTableXML;
import java.awt.Component;
import java.util.ArrayList;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import pojo.Foreignkey;
import pojo.Property;

/**
 *
 * @author HoangLiem
 */
public class AddForeignKeyDialog extends javax.swing.JDialog {
    
    private String databaseName;
    private String tableName;
    
    public String getDatabaseName() {
        return databaseName;
    }
    
    public void setDatabaseName(String databaseName) {
        this.databaseName = databaseName;
    }
    
    public String getTableName() {
        return tableName;
    }
    
    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    /** Creates new form AddForeignKeyDialog */
    public AddForeignKeyDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    void initTable() {
        ArrayList<ArrayList<Object>> data = new ArrayList<ArrayList<Object>>();
        ArrayList<String> fieldsTable = ExecTableXML.getAllFieldsFromTable(databaseName, tableName);
        if (fieldsTable != null) {
            for (int i = 0; i < fieldsTable.size(); i++) {
                ArrayList<Object> obj = new ArrayList<Object>();
                obj.add(fieldsTable.get(i));
                obj.add(new Boolean(false));
                obj.add(new String(""));
                data.add(obj);
            }
        }
        AddForeignkeyModel model = new AddForeignkeyModel(data);
        jtbReferences.setModel(model);
        initColumnSizes(jtbReferences);
        
        String tableRef = (String) jcbTableRef.getSelectedItem();
        ArrayList<Property> ids = ExecIdXML.getIdsOfTable(databaseName, tableRef);
        TableCellEditor editor = setComboboxIdRefCol(ids);
        jtbReferences.getColumnModel().getColumn(2).setCellEditor(editor);
    }
    
    private void initColumnSizes(JTable table) {
        AddForeignkeyModel model = (AddForeignkeyModel) table.getModel();
        TableColumn column = null;
        Component comp = null;
        int headerWidth = 0;
        int cellWidth = 0;
        ArrayList<Object> longValues = model.getLongValues();
        TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
        
        for (int i = 0; i < model.getColumnCount(); i++) {
            column = table.getColumnModel().getColumn(i);
            comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
            comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, longValues.get(i), false, false, 0, i);
            headerWidth = comp.getPreferredSize().width;
            cellWidth = comp.getPreferredSize().width;
            column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        }
    }
    
    public TableCellEditor setComboboxIdRefCol(ArrayList<Property> ids) {
        TableCellEditor tce;
        JComboBox comboBox = new JComboBox();
        if (ids != null && !ids.isEmpty()) {
            for (int i = 0; i < ids.size(); i++) {
                comboBox.addItem(ids.get(i).getName());
            }
        }
        tce = new DefaultCellEditor(comboBox);
        return tce;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jcbTableRef = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbReferences = new javax.swing.JTable();
        jlabelMessage = new javax.swing.JLabel();
        jbtAdd = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(300, 200));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setText("Table reference:");

        jcbTableRef.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbTableRefActionPerformed(evt);
            }
        });

        jtbReferences.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtbReferences);

        javax.swing.GroupLayout jPanelLayout = new javax.swing.GroupLayout(jPanel);
        jPanel.setLayout(jPanelLayout);
        jPanelLayout.setHorizontalGroup(
            jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelLayout.createSequentialGroup()
                .addGap(59, 59, 59)
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addComponent(jcbTableRef, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(54, 54, 54)
                .addComponent(jlabelMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(53, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 535, Short.MAX_VALUE)
        );
        jPanelLayout.setVerticalGroup(
            jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jcbTableRef, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jlabelMessage))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE))
        );

        jbtAdd.setText("OK");
        jbtAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtAddActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(239, 239, 239)
                .addComponent(jbtAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtAdd)
                .addContainerGap(16, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    void setComboboxTableRef() {
        ArrayList<String> tableNames = ExecTableXML.getNameOfTableHasID(databaseName);
        if (tableNames != null && !tableNames.isEmpty()) {
            for (int i = 0; i < tableNames.size(); i++) {
                jcbTableRef.addItem(tableNames.get(i));
            }
        }
    }
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        setComboboxTableRef();
        initTable();
    }//GEN-LAST:event_formWindowOpened
    
    private void jcbTableRefActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbTableRefActionPerformed
        // TODO add your handling code here:
        initTable();
    }//GEN-LAST:event_jcbTableRefActionPerformed
// ArrayList<String> proRef = new ArrayList<String>();
    //  ArrayList<String> idsRef = new ArrayList<String>();
    // String propertyRef = "";
    // String idsRef = "";
            /*
     * if (propertyRef.equals("")) {
    propertyRef = propertyRef + field;
    idsRef = idsRef + idRef;
    } else {
    propertyRef = propertyRef + "," + field;
    idsRef = idsRef + "," + idRef;
    }
     */
    private void jbtAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtAddActionPerformed
        // TODO add your handling code here:

        AddForeignkeyModel model = (AddForeignkeyModel) jtbReferences.getModel();
        ArrayList<ArrayList<Object>> data = model.getData();
        String tableRef = (String) jcbTableRef.getSelectedItem();
        if (data != null && !data.isEmpty()) {
            for (int i = 0; i < data.size(); i++) {
                ArrayList<Object> obj = data.get(i);
                if (obj != null && !obj.isEmpty()) {// co 3 gia tri trong obj
                    String field = (String) obj.get(0);
                    boolean isFK = (Boolean) obj.get(1);
                    String idRef = (String) obj.get(2);
                    if (isFK) {
                        Foreignkey fk = new Foreignkey(field, tableRef, idRef);
                        String error = "";
                        if (!ExecForeignkeyXML.checkedType(databaseName, tableName, fk)) {
                            error = "No same type";
                        }
                        if (ExecForeignkeyXML.checkedExistedFk(databaseName, tableName, fk)) {
                            error = "Foreign key has existed";
                        }
                        boolean result = ExecForeignkeyXML.addFkToTable(databaseName, tableName, fk);
                        if (result) {
                            // JOptionPane.showMessageDialog(this, "Add foreign key successfully");
                        } else {
                            JOptionPane.showMessageDialog(this, "Can not reference from " + field + " to " + idRef + "! " + error);
                        }
                    }
                }
            }
            jlabelMessage.setText("Completed !");
            //JOptionPane.showMessageDialog(this, "Add foreign key completed");
        }
        
    }//GEN-LAST:event_jbtAddActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AddForeignKeyDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AddForeignKeyDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AddForeignKeyDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AddForeignKeyDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            
            public void run() {
                AddForeignKeyDialog dialog = new AddForeignKeyDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtAdd;
    private javax.swing.JComboBox jcbTableRef;
    private javax.swing.JLabel jlabelMessage;
    private javax.swing.JTable jtbReferences;
    // End of variables declaration//GEN-END:variables
}
